<?php

namespace Modules\Base\Repository;

use App\Services\UnitService;
use Illuminate\Support\Facades\DB;
use Modules\Base\Models\BoxTurnover;
use Modules\Production\Models\PickOrderDetailSplit;
use Modules\Production\Repository\PickOrderRepository;

class BoxTurnoverRepository
{

    /**
     * 根据单据ID获取一条周转记录
     * @param $orderId
     * @return mixed
     */
    static public function getBoxTurnoverOneByOrderId($orderId,$docType){
        return BoxTurnover::where('order_id',$orderId)->where('doc_type',$docType)->first();
    }

    /**
     * 根据箱号获取一条周转信息
     * @param $lotnum
     * @return mixed
     */
    static public function getBoxTurnoverByLotnum($lotnum){
        return BoxTurnover::where('lot_num',$lotnum)->first();
    }

    /**
     * 根据单据ID删除所属的全部周转记录
     * @param $orderId
     * @param $docType
     * @return mixed
     */
    static public function deleteByLotnum($lotnum){
        return BoxTurnover::where('lot_num',$lotnum)->delete();
    }

    /**
     * 保存一条周转记录
     * @param $data
     * @return mixed
     */
    static public function save($data){
        return BoxTurnover::create($data);
    }

    /**
     * 领料箱号修改提交处理
     * @param $postData
     */
    static public function changeSubmit($postData){

        try{

            DB::beginTransaction();

            $split = [];
            foreach ($postData as $item){
                $pickOrder = PickOrderRepository::getPickDetailWithOrderById($item['pick_detail_id']);
                if( ($item['qty'] + $pickOrder->split_qty) > $pickOrder->qty){
                    throw new \Exception("箱号[{$pickOrder->lot_num}]可拆数量不足");
                }
                $split[] = [
                    'pick_order_id'     => $pickOrder->order->id,
                    'pick_detail_id'    => $pickOrder->id,
                    'material_no'       => $pickOrder->material_no,
                    'lot_num'           => $item['to_lot_num'],
                    'qty'               => $item['qty'],
                    'creator_id'        => UnitService::getUserId(),
                    'created_at'        => time(),
                    'updated_at'        => time(),
                ];
                PickOrderRepository::incSplitQty($pickOrder->id,$item['qty']);
            }

            (new PickOrderDetailSplit())->insert($split);

            DB::commit();
            return true;
        }catch (\Exception $e){
            DB::rollBack();
            throw $e;
        }

    }

}
